<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="库存日期" prop="storeDate">
        <el-date-picker clearable
          v-model="queryParams.storeDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择库存日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属仓库" prop="storeKind">
        <el-select v-model="queryParams.storeKind" placeholder="请选择所属仓库" clearable>
          <el-option
            v-for="dict in dict.type.store_kind"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品编码" prop="goodsCode">
        <el-input
          v-model="queryParams.goodsCode"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--
      </el-form-item>
      <el-form-item label=" total" prop="storeTotalNum">
        <el-input
          v-model="queryParams.storeTotalNum"
          placeholder="请输入 total"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:store:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:store:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:store:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['shop:store:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList"
    row-key="id"
    default-expand-all
    :tree-props="{children: 'shopStoreChildList', hasChildren: 'hasChildren'}"
    @selection-change="handleSelectionChange">

      <!-- <el-table-column align="center" type="expand">
        <template #default="scopes">
         scopes.row.list的list是后端返给前端大数组中的子数组名称，list改为你的子数组名称即可
          <el-table:data="scopes.row.list">
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="创建时间" prop="create_time"></el-table-column>
        </el-table>
        </template>

      </el-table-column> -->

      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="库存日期" align="center" prop="storeDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.storeDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属仓库" align="center" prop="storeKind">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.store_kind" :value="scope.row.storeKind"/>
        </template>
      </el-table-column>

      <el-table-column prop="" label="序号" align="center" width="150">
        <template slot-scope="scope">
          {{scope.row.index}}
        </template>
      </el-table-column>
      <el-table-column label="商品编码" align="center" prop="goodsCode" />
      <el-table-column label="商品名称" align="center" prop="goodsName"  width="260"/>
      <el-table-column label="规格型号" align="center" prop="goodsGg" />
      <!-- <el-table-column label="单位" align="center" prop="goodsUnit" /> -->
      <el-table-column label="昨日出库数(件)" align="center" prop="goodsStoreNum" />
      <el-table-column label="剩余库存(件)" align="center" prop="goodsStoreRemain" />
      <el-table-column label="库存金额(元)" align="center" prop="goodsTotalPrice" />
      <el-table-column label="合计库存总数(件)" align="center" prop="storeTotalNum" />
      <el-table-column label="合计总金额(元)" align="center" prop="storeTotalPrice" />
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <div v-if="scope.row.storeDate != null">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['shop:store:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['shop:store:remove']"
            >删除</el-button>
            </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改电商商品库存对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row >
          <el-col :span="6">
           <el-form-item label="库存日期" prop="storeDate">
             <el-date-picker clearable
               v-model="form.storeDate"
               type="date"
               value-format="yyyy-MM-dd"
               placeholder="请选择库存日期">
             </el-date-picker>
           </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="所属仓库" prop="storeKind">
              <el-select v-model="form.storeKind" placeholder="请选择所属仓库" @change="addStoreChildByKind">
                <el-option
                  v-for="dict in dict.type.store_kind"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库存总数" prop="storeTotalNum">
              <!-- <el-input v-model="form.storeTotalNum" placeholder="请输入库存总数" disabled/> -->
              {{form.storeTotalNum}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合计总金额(元)" prop="storeTotalPrice">
              {{form.storeTotalPrice}}
              <!-- <el-input v-model="form.storeTotalPrice"  disabled/> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="4">
            <el-form-item label="录入时间" prop="createTime">
              <el-input v-model="form.createTime" type="textarea"  disabled/>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-divider content-position="center">商品信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddShopStoreChild">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteShopStoreChild">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="shopStoreChildList" :row-class-name="rowShopStoreChildIndex" @selection-change="handleShopStoreChildSelectionChange" ref="shopStoreChild"  width="1500px" >
          <el-table-column type="selection"  align="center" />
          <!-- <el-table-column label="序号" width="5%" align="center" prop="index" /> -->

          <el-table-column label="商品名称" prop="goodsName">
            <template slot-scope="scope">
              <el-select v-model="scope.row.goodsName" placeholder="请选择商品名称" @change="selectGoods" @title="scope.row.goodsName">
                <el-option
                  v-for="dict in goodsList"
                  :label="dict.goodsName"
                  :value="dict.goodsName"
                ></el-option>
              </el-select>
              <!-- <el-input v-model="scope.row.goodsName" placeholder="请输入商品名称" /> -->
            </template>
          </el-table-column>
          <el-table-column label="商品编码" prop="goodsCode" width="200">
            <template slot-scope="scope">
              {{scope.row.goodsCode}}
              <!-- <el-input v-model="scope.row.goodsCode" placeholder="请输入商品编码" /> -->
            </template>
          </el-table-column>
          <el-table-column label="商品单位" prop="goodsUnit" width="100">
            <template slot-scope="scope">
              {{scope.row.goodsUnit}}
              <!-- <el-input v-model="scope.row.goodsUnit" placeholder="请输入商品单位" /> -->
            </template>
          </el-table-column>
          <!--<el-table-column label="商品规格" prop="goodsGg" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.goodsGg" placeholder="请输入商品规格" />
            </template>
          </el-table-column> -->
          <el-table-column label="单价(元)" prop="goodsPrice" width="100">
            <template slot-scope="scope">
              {{scope.row.goodsPrice}}
            </template>
          </el-table-column>
          <el-table-column label="单件瓶碗数" prop="goodsUnitPiece"  width="150">
            <template slot-scope="scope">
              {{scope.row.goodsUnitPiece}}
              <!-- <el-input v-model="scope.row.goodsUnitPiece" placeholder="请输入单件瓶碗数" /> -->
            </template>
          </el-table-column>
          <el-table-column label="昨日出库数(件)" prop="goodsStoreNum"  width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.goodsStoreNum" placeholder="请输入昨日出库数(件)" />
            </template>
          </el-table-column>
          <el-table-column label="今日剩余库存数(件)" prop="goodsStoreRemain"  width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.goodsStoreRemain" placeholder="请输入今日剩余库存数(件)" @input="countStoreTotal"/>
            </template>
          </el-table-column>
          <el-table-column label="单品总价(元)" prop="goodsTotalPrice"   width="150">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.goodsTotalPrice" disabled /> -->
              {{scope.row.goodsTotalPrice}}
            </template>
          </el-table-column>
          <el-input type="hidden" name="storeKind" value=""/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStore, getStore, delStore, addStore, updateStore,getGoodsList,goodsListByKind } from "@/api/shop/store";

// import ElementPlus from 'element-plus'
// import 'element-plus/dist/index.css'

export default {
  name: "Store",
  dicts: ['store_kind'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedShopStoreChild: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电商商品库存表格数据
      storeList: [],
      goodsList: [],
      // ${subTable.functionName}表格数据
      shopStoreChildList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,        storeDate: null,        storeTotalNum: null  ,storeKind: null,goodsCode: null,goodsName: null    },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeDate: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        storeKind: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询电商商品库存列表 */
    getList() {
      this.loading = true;
      listStore(this.queryParams).then(response => {
        this.storeList = response.rows;
        this.storeList.forEach(store => {
          let index = 1
          store.shopStoreChildList.forEach(child => {
            child.index = index
            index++
          })
        })
        console.log("this.storeList>>>>>",JSON.stringify(this.storeList))
        this.total = response.total;
        this.loading = false;
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        remark: null,        status: "0",        delFlag: null,        createBy: null,        createTime: null,        updateBy: null,        updateTime: null,        storeDate: null,        storeTotalNum: null,        storeTotalPrice: null      };
      this.shopStoreChildList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加电商商品库存";
      getGoodsList().then(response => {
        this.goodsList = response.data;
        // console.log("this.goodsList>>>>>",JSON.stringify(this.goodsList))
      });

    },
    addStoreChildByKind(){
      let storeKind = this.form.storeKind
       console.log("storeKind>>>>>",JSON.stringify(storeKind))
      goodsListByKind(storeKind).then(response => {
        let shopChild = response.data;
       console.log("shopChild>>>>>",JSON.stringify(shopChild))
       shopChild.forEach(child => {
         this.autoAddShopStoreChild(child)
       })
      });
    },
    /** ${subTable.functionName}添加按钮操作 */
    autoAddShopStoreChild(shopChild) {
      let obj = {};
      obj.goodsCode = shopChild.goodsCode;
      obj.goodsName = shopChild.goodsName;
      obj.goodsGg = shopChild.goodsGg;
      obj.goodsUnit = shopChild.goodsUnit;
      obj.goodsPrice = shopChild.goodsPrice;
      obj.goodsUnitPiece = shopChild.goodsUnitPiece;
      obj.goodsStoreNum = 0;
      obj.goodsStoreRemain = 0;
      obj.goodsTotalPrice = 0;
      obj.storeKind = shopChild.storeKind;
      this.shopStoreChildList.push(obj);
    },
    //汇总总库存数
    countStoreTotal(){
      var storeTotal = 0
      var storeTotalPrice = 0.00
        // console.log("this.shopStoreChildList>>>>>",JSON.stringify(this.shopStoreChildList))
      this.shopStoreChildList.forEach(goods=>{
      // console.log("goods.goodsStoreRemain>>",goods.goodsStoreRemain)
        if(goods.goodsStoreRemain != null && goods.goodsStoreRemain != ''){
          storeTotal += Number(goods.goodsStoreRemain)
          goods.goodsTotalPrice = parseFloat(Number(goods.goodsStoreRemain) * Number(goods.goodsUnitPiece) * Number(goods.goodsPrice) ).toFixed(2)
          storeTotalPrice += Number(goods.goodsTotalPrice)
        }
      })
      // console.log("storeTotal>>",storeTotal)
      if(storeTotal != 0){
        this.form.storeTotalNum = storeTotal
        this.form.storeTotalPrice = parseFloat(storeTotalPrice).toFixed(2)
      }
    },
    selectGoods(obj){
      var goodsObj = null
      this.goodsList.forEach(goods=>{
        let goodsName = goods.goodsName
        if(goodsName === obj){
          goodsObj = goods
        }
      })
      console.log("goodsObj>>>",JSON.stringify(goodsObj))
      this.shopStoreChildList.forEach(item => {
        let goodsName = item.goodsName
        if(goodsName === obj){
          item.goodsCode = goodsObj.goodsCode
          item.goodsId = goodsObj.goodsId;
          item.goodsGg = goodsObj.goodsGg;
          item.goodsUnit = goodsObj.goodsUnit;
          item.goodsPrice = goodsObj.goodsPrice;
          item.goodsUnitPiece = goodsObj.goodsUnitPiece;
          item.storeKind = this.form.storeKind
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStore(id).then(response => {
        this.form = response.data;
        this.shopStoreChildList = response.data.shopStoreChildList;
        this.open = true;
        this.title = "修改电商商品库存";

      });
      getGoodsList().then(response => {
        this.goodsList = response.data;
        // console.log("this.goodsList>>>>>",JSON.stringify(this.goodsList))
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.shopStoreChildList = this.shopStoreChildList;
      var isNum = true
      var isRemain = true
      this.shopStoreChildList.forEach(shopStoreChild => {
        console.log(">>>>>>>>>>>>>>")
        if(shopStoreChild.goodsStoreNum === null || shopStoreChild.goodsStoreNum === ''){
          this.$modal.msgError("昨日出库件数不能为空")
          isNum = false
          return
        }
        if(shopStoreChild.goodsStoreRemain === null || shopStoreChild.goodsStoreRemain === ''){
          this.$modal.msgError("今日剩余库存数不能为空")
          isRemain = false
          return
        }
      })
      if(isNum && isRemain){
        this.$refs["form"].validate(valid => {
          if (valid) {

            if (this.form.id != null) {
              updateStore(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addStore(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除电商商品库存编号为"' + ids + '"的数据项？').then(function() {
        return delStore(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** ${subTable.functionName}序号 */
    rowShopStoreChildIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** ${subTable.functionName}添加按钮操作 */
    handleAddShopStoreChild() {
      let obj = {};
      obj.remark = "";
      obj.status = "";
      obj.goodsId = "";
      obj.goodsCode = "";
      obj.goodsName = "";
      obj.goodsGg = "";
      obj.goodsUnit = "";
      obj.goodsPrice = "";
      obj.goodsUnitPiece = "";
      obj.goodsStoreNum = "";
      obj.goodsStoreRemain = "";
      obj.goodsTotalPrice = "";
      obj.storeKind = "";
      this.shopStoreChildList.push(obj);
    },
    /** ${subTable.functionName}删除按钮操作 */
    handleDeleteShopStoreChild() {
      if (this.checkedShopStoreChild.length == 0) {
        this.$modal.msgError("请先选择要删除的${subTable.functionName}数据");
      } else {
        const shopStoreChildList = this.shopStoreChildList;
        const checkedShopStoreChild = this.checkedShopStoreChild;
        this.shopStoreChildList = shopStoreChildList.filter(function(item) {
          return checkedShopStoreChild.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleShopStoreChildSelectionChange(selection) {
      this.checkedShopStoreChild = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('shop/store/export', {
        ...this.queryParams
      }, `store_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
